package com.chanta.server.services;

import java.util.List;

import javax.jdo.Query;

import com.chanta.client.services.UserRegistrationService;
import com.chanta.server.helper.BCrypt;
import com.chanta.server.persistence.ChantaPersistanceMan;
import com.chanta.server.persistence.User;
import com.chanta.shared.ChantaException;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * TODO Please comment this class..
 * 
 * @author Hakan Özdemir - Vendoo Inc.
 * @date 30.06.2013
 * 
 */
@SuppressWarnings("serial")
public class UserRegistrationServiceImpl extends RemoteServiceServlet implements
		UserRegistrationService {

	@Override
	public String login(String username, String password) throws IllegalArgumentException {
		// TODO Auto-generated method stub
		String salt = BCrypt.gensalt();
		String hashed = BCrypt.hashpw(password, salt);
		return "User logged in [" + username + ", " + hashed + "]";
	}

	@Override
	public boolean createUser(String username, String password) throws ChantaException {

		String salt = BCrypt.gensalt();
		String hashedpwd = BCrypt.hashpw(password, salt);

		User user = new User(username, hashedpwd);

		Query query = ChantaPersistanceMan.getPersistentManager().newQuery(User.class);
		query.setFilter("email == emailParam");
		query.declareParameters("String emailParam");

		List<User> execute = (List<User>) query.execute(username);
		if (!execute.isEmpty()) {
			throw new ChantaException("User existiert bereits");
		}

		user = ChantaPersistanceMan.getPersistentManager().makePersistent(user);

		return Boolean.TRUE.booleanValue();
	}
}
